package com.stone.business.workcard.action;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.opensymphony.xwork2.Preparable;
import com.stone.business.gzrwd.pojo.TGzrwd;
import com.stone.business.gzrwd.pojo.TGzrwdRw;
import com.stone.business.plan.pojo.TPlan;
import com.stone.business.workcard.pojo.Gxzlkzk_BZ;
import com.stone.business.workcard.pojo.MainWorkCardOne;
import com.stone.business.workcard.pojo.MapType;
import com.stone.business.workcard.pojo.Ryzzfg;
import com.stone.business.workcard.pojo.WorkCardOne_BZ;
import com.stone.business.workcard.pojo.Wxdfx;
import com.stone.business.workcard.service.WorkcardService;
import com.stone.common.pojo.TFile;
import com.stone.para.IConstant;
import com.stone.sys.pojo.TUser;
import com.stone.utils.DateFormatTool;
import com.stone.utils.FileUtils;
import com.stone.utils.Resources;
import com.stone.utils.StringUtils;

import frm.ssh.action.BaseAction;
import frm.ssh.exception.AppException;
/**
 * 班组作业控制卡（二种票）
 * @author Administrator
 *
 */
public class WorkcardTwoAction extends BaseAction  implements Preparable{

	private WorkcardService workcardService;
	private List<MapType> listcheckbox;
	private MainWorkCardOne entity=new MainWorkCardOne();
	private File myFile;
	// 下载用 返回的文件流
	protected InputStream returnStream;
	// 下载用的名字
	protected String downFileName;
	private String myFileFileName;
	private String id;
	private List<WorkCardOne_BZ> workCardOneBZList;
	private List<Ryzzfg> ryzzfgList;
	private List<Wxdfx> wxdfxList;
	private String directFlag;
	private String bdzid;
	private String picUrl;
	public void initCheckBox(){
		listcheckbox=workcardService.findListBySql("select oc_dm as keyid,oc_name as keyname from tab_Ty_Dm where oc_yxbz='T' and oc_lb='002'");
		
		}
   
    public void prepare() throws Exception {
    	initCheckBox();
    }

	public String initPage(){
		initCheckBox();		
		if(!StringUtils.isNullOrBlankFull(id)) {
		List<TGzrwdRw> listRwd  = workcardService.findListByHql("from TGzrwdRw where gzrwdid =" + id);
		TGzrwd tGzrwd = (TGzrwd)workcardService.findById(Long.parseLong(id), TGzrwd.class.getName());//取得工作任务单pojo
		TUser tUser=(TUser)workcardService.findById(Long.parseLong(tGzrwd.getZbz()==null?"0":tGzrwd.getZbz().trim()), TUser.class.getName());//取得班组pojo
		this.entity.setPno(tGzrwd.getGzpno());
		if(entity!=null&&"".equals(entity.getBxr())||entity.getBxr()==null){
			TUser sessionUser=(TUser)super.getSession().getAttribute(IConstant.SESSION_TUSER);		
			entity.setBxr(sessionUser.getName());
			entity.setCjrid(sessionUser.getId());
		}
		String users=tUser==null?"":tUser.getName()+","+tGzrwd.getZbyname();		
		ryzzfgList=new ArrayList<Ryzzfg>();		
		for(TGzrwdRw tGzrwdRw:listRwd){			
			Ryzzfg ryzzfg=new Ryzzfg();
			ryzzfg.setOc_zynr(tGzrwdRw.getGznr());
			ryzzfg.setOc_zyry(users);
			ryzzfgList.add(ryzzfg);
		}
		}
		return SUCCESS;
	}
	public String addWorkcardTwo(){
		
		// 判断文件大小 不大于10M
		System.out.println("myFileName:"+myFileFileName+"myFile"+myFile==null);
		if (myFileFileName != null
				&& myFile == null && (myFile.length() > IConstant.FILE_BUFFER_SIZE
						* IConstant.FILE_SIZE_TEN * IConstant.FILE_SIZE_HUNDRED)) {
			super.setInfo("上传失败，附件不能超过1M");//OUTOFSIZE
			return SUCCESS;
		}
		TFile tFile=null;
		if(myFile!=null){
		// 文件存到服务器的名字
		String saveFileName = FileUtils.getFileName(myFileFileName)
				+ "_"
				+ DateFormatTool.format(new Date(), true).replace(" ", "")
						.replaceAll("-", "").replaceAll(":", "")
				+ FileUtils.getExtention(myFileFileName);
		
		//String path = Resources.getString((String)super.getSession().getAttribute("uploadpath"), "struts");
      String path = Resources.getString("uploadpath", "struts");
		if ("EXCEPTION_STRING".equals(path)) {
			super.setInfo("没有指定上传路径");//PATHERROR
			
		}

		FileUtils.createFolder(path);
		tFile = new TFile();
		// 创建一个文件
		File saveFile = new File(path + saveFileName);

		String s = saveFileName;

		try {

			// 上传文件
			org.apache.commons.io.FileUtils.copyFile(myFile, saveFile);

			
			tFile.setUrl(path);
			//tFile.setTableid(Long.parseLong((String)super.getSession().getAttribute("tableid")));
			//tFile.setColname((String)super.getSession().getAttribute("colname"));
			tFile.setFilename(myFileFileName);
			tFile.setRealfilename(saveFileName);
			tFile.setOperuser(((TUser) super.getSession().getAttribute(
					IConstant.SESSION_TUSER)).getId());
			tFile.setOperdate(DateFormatTool.formatToDate(workcardService
					.getSysdate("yyyy-MM-dd HH24:mi"), true));
			
			// 是否是图片
			if (IConstant.IMAGE_TYPE.indexOf(FileUtils.getExtention(myFileFileName).toUpperCase()) != -1) {
				tFile.setImageflag("1");
			} else {
				tFile.setImageflag("0");
			}
		} catch (Exception e) {
			e.printStackTrace();
			// 上传后信息
			super.setInfo(s);
			s = "文件上传出现错误";
			throw new AppException("上传失败");
		}
		}	
		String check_tools="";
		if(this.entity!=null&&this.entity.getChecked_tools()!=null&&this.entity.getChecked_tools().length!=0){
		for(String tmpcheck_tools:entity.getChecked_tools()){
			check_tools+=tmpcheck_tools+",";
		}
		check_tools=check_tools.substring(0, check_tools.length()-1);
		entity.setCheck_tools(check_tools);
		}
		entity.setOc_yxbz("T");
		
		entity.setDt_czrq(DateFormatTool.formatToDate(workcardService.getSysdate("yyyy-MM-dd HH24:mi"), true));
		TUser tUser=(TUser)super.getSession().getAttribute(IConstant.SESSION_TUSER);
		entity.setOc_czry(tUser.getName());
		if(("".equals(entity.getBxr())||entity.getBxr()==null)){	
		entity.setCjrid(tUser.getId());
		entity.setBxr(tUser.getName());
		
		}
		//获取图片picURL added by wangtao 2012-08-31
		if (entity != null && entity.getPlanid() != null) {
			String sql = " from TPlan where id = " + entity.getPlanid();
			TPlan tplan = (TPlan)workcardService.findFirst(sql);
			if(tplan != null)
				//this.setBdzid(tplan.getStationid());
			
			sql = " from TFile where tableid = '" + entity.getId_sno() + "' AND colname = 'TAB_SECURITY_PIC'";
			TFile tfile = (TFile)workcardService.findFirst(sql);
			if(tfile != null)
				this.setPicUrl(tfile.getUrl());
			
		}
		String rtn=workcardService.doSave(entity, workCardOneBZList,ryzzfgList,wxdfxList,tFile);
		
		System.out.println(entity.getCheck_tools()+">>>>>>>>>"+check_tools);
		super.setInfo(rtn);
		
		return "ADD_SUCCESS";
	}

	public String updateWorkcardTwo() {
		initCheckBox();
		if (!StringUtils.isNullOrBlankFull(id)) {
			this.entity = (MainWorkCardOne) workcardService.findById(Long.parseLong(id), MainWorkCardOne.class.getName());
			workCardOneBZList = workcardService.findListByHql("from WorkCardOne_BZ where p_idsno='" + this.entity.getId_sno() + "'");
			ryzzfgList = workcardService
					.findListByHql("from Ryzzfg where p_idsno='"
							+ this.entity.getId_sno() + "'");
			wxdfxList = workcardService
					.findListByHql("from Wxdfx where p_idsno='"
							+ this.entity.getId_sno() + "'");

		}
		
		//获取变电站ID added by Cheng 2012-6-20
		if (entity != null && entity.getPlanid() != null) {
			String sql = " from TPlan where id = " + entity.getPlanid();
			TPlan tplan = (TPlan)workcardService.findFirst(sql);
			if(tplan != null)
				this.setBdzid(tplan.getStationid());
			
			sql = " from TFile where tableid = '" + entity.getId_sno() + "' AND colname = 'TAB_SECURITY_PIC'";
			TFile tfile = (TFile)workcardService.findFirst(sql);
			if(tfile != null)
				this.setPicUrl(tfile.getUrl());
		}
		
		if (entity != null && entity.getCheck_tools() != null) {
			String[] mycheck_tools = entity.getCheck_tools().split(",");
			entity.setChecked_tools(mycheck_tools);
		}
		if (entity != null && entity.getSh_status() != null) {
			String sh_Name = ((entity.getSh_status().equals("0")) ? "审核不通过"
					: (entity.getSh_status().equals("1") ? "审核通过" : "待审核"));
			entity.setSh_status_name(sh_Name);
		}
		if (entity != null && "".equals(entity.getBxr())
				|| entity.getBxr() == null) {
			TUser sessionUser = (TUser) super.getSession().getAttribute(
					IConstant.SESSION_TUSER);
			entity.setBxr(sessionUser.getName());
			entity.setCjrid(sessionUser.getId());
		}
		if (directFlag == null || directFlag.equals("")) {
			return "UPDATE_SUCCESS";
		} else {
			if (directFlag.equals("PRINT_SUCCESS")) {
				if (workCardOneBZList.size() == 0) {
					for (int i = 0; i < 4; i++) {
						WorkCardOne_BZ bz = new WorkCardOne_BZ();
						workCardOneBZList.add(bz);
					}
				}
			}
			return directFlag;
		}
	}
	public String skipByPlanid(){
		initCheckBox();
		
		this.entity = (MainWorkCardOne)workcardService.findFirst(" from MainWorkCardOne t where t.oc_type='02' and  t.planid='"+this.entity.getPlanid()+"'");
		if(this.entity!=null){
			workCardOneBZList=workcardService.findListByHql("from WorkCardOne_BZ where p_idsno='"+this.entity.getId_sno()+"'");
			ryzzfgList=workcardService.findListByHql("from Ryzzfg where p_idsno='"+this.entity.getId_sno()+"'");
			wxdfxList=workcardService.findListByHql("from Wxdfx where p_idsno='"+this.entity.getId_sno()+"'");
			
		}
		if(entity!=null&&entity.getCheck_tools()!=null){
		String[] mycheck_tools=entity.getCheck_tools().split(",");
		entity.setChecked_tools(mycheck_tools);			
		}
		
		if(entity!=null&&entity.getSh_status()!=null){
		String sh_Name=((entity.getSh_status().equals("0"))?"审核不通过":(entity.getSh_status().equals("1")?"审核通过":"待审核"));
		entity.setSh_status_name(sh_Name);
		}
		
		//获取变电站ID added by Cheng 2012-6-20
		if (entity != null && entity.getPlanid() != null) {
			String sql = " from TPlan where id = " + entity.getPlanid();
			TPlan tplan = (TPlan)workcardService.findFirst(sql);
			if(tplan != null)
				this.setBdzid(tplan.getStationid());
			
			sql = " from TFile where tableid = '" + entity.getId_sno() + "' AND colname = 'TAB_SECURITY_PIC'";
			TFile tfile = (TFile)workcardService.findFirst(sql);
			if(tfile != null)
				this.setPicUrl(tfile.getUrl());
		}
		
		if(entity!=null&&("".equals(entity.getBxr())||entity.getBxr()==null)){
			TUser tUser=(TUser)super.getSession().getAttribute(IConstant.SESSION_TUSER);		
			entity.setBxr(tUser.getName());
		}
		
		if(entity==null){			
			entity=new MainWorkCardOne();
			if(!StringUtils.isNullOrBlankFull(id)) {
				List<TGzrwdRw> listRwd  = workcardService.findListByHql("from TGzrwdRw where gzrwdid =" + id);
				TGzrwd tGzrwd = (TGzrwd)workcardService.findById(Long.parseLong(id), TGzrwd.class.getName());//取得工作任务单pojo
				TUser tUser=(TUser)workcardService.findById(Long.parseLong(tGzrwd.getZbz()==null?"0":tGzrwd.getZbz().trim()), TUser.class.getName());//取得班组pojo
				this.entity.setPno(tGzrwd.getGzpno());
				this.entity.setPlanid(tGzrwd.getPlanid().toString());
				if(entity!=null&&"".equals(entity.getBxr())||entity.getBxr()==null){
					TUser sessionUser=(TUser)super.getSession().getAttribute(IConstant.SESSION_TUSER);		
					entity.setBxr(sessionUser.getName());
					entity.setCjrid(sessionUser.getId());
					entity.setSh_status("2");
		            entity.setOc_type("02");//设置票种  该处为二种票
				}
				String users=tUser==null?"":tUser.getName()+","+tGzrwd.getZbyname();		
				ryzzfgList=new ArrayList<Ryzzfg>();		
				for(TGzrwdRw tGzrwdRw:listRwd){			
					Ryzzfg ryzzfg=new Ryzzfg();
					ryzzfg.setOc_zynr(tGzrwdRw.getGznr());
					ryzzfg.setOc_zyry(users);
					ryzzfgList.add(ryzzfg);
				}
				}
		}
		return "SKIP_SUCCESS";
	}
	/**
	 * 批量删除班组作业控制卡（二种票）
	 * @return
	 */
	public String deleteWorkcardTwo(){
		if(!StringUtils.isNullOrBlankFull(id)) {
			workcardService.deleteByDHql(" p_idsno in("+id+")",null,Ryzzfg.class.getName());
			workcardService.deleteByDHql(" p_idsno in("+id+")",null,WorkCardOne_BZ.class.getName());
			workcardService.deleteByDHql(" p_idsno in("+id+")",null,Wxdfx.class.getName());
			workcardService.doDelAll(id,MainWorkCardOne.class.getName());
		
		}
		
		return "DELETE_SUCCESS";
	}
	public void deleteDetail() throws Exception {
	String deltype=super.getRequest().getParameter("deltype");
	if(deltype.equals("1")){
		workcardService.doDelAll(id, "Ryzzfg");
		}else if(deltype.equals("2")){
		workcardService.doDelAll(id, "Wxdfx");
		}else if(deltype.equals("3")){
		workcardService.doDelAll(id, "WorkCardOne_BZ");
		}
        super.getResponse().getWriter().print("{msg:'删除成功'}");
	}
	/**
	 * 批量审核班组作业控制卡（二种票）
	 * @return
	 */
	public String verifyWorkcardTwo_PL(){
		if(!StringUtils.isNullOrBlankFull(id)) {
			TUser tUser=(TUser)super.getSession().getAttribute(IConstant.SESSION_TUSER);		
			workcardService.update(" sh_status='1',sp='"+tUser.getName()+"'"," id_sno in ("+id+")",MainWorkCardOne.class.getName());		
		}
		return "SH_SUCCESS_PL";
	}
	/**
	 * 审核班组作业控制卡（二种票）
	 * @return
	 */
	public String verifyWorkcardTwo(){
		if(!StringUtils.isNullOrBlankFull(id)) {
			TUser tUser=(TUser)super.getSession().getAttribute(IConstant.SESSION_TUSER);
			workcardService.update(" sh_status='1',sp='"+tUser.getName()+"'"," id_sno='"+id+"'",MainWorkCardOne.class.getName());		
		}
		String info="审核成功!";
		super.setInfo(info);
		return "SH_SUCCESS";
	}	
	public String fileDownload() throws AppException, FileNotFoundException {
		System.out.println("图片ID："+id);		
		
		TFile tFile = (TFile) workcardService.findById(Long.parseLong(id.trim()), TFile.class.getName());
		
		
		returnStream = new java.io.FileInputStream(tFile.getUrl() + tFile.getRealfilename());

		downFileName = tFile.getFilename();
		
		return "DOWNLOAD_SUCCESS";

	}
	public List<MapType> getListcheckbox() {
		return listcheckbox;
	}
	public void setListcheckbox(List<MapType> listcheckbox) {
		this.listcheckbox = listcheckbox;
	}
	public File getMyFile() {
		return myFile;
	}
	public void setMyFile(File myFile) {
		this.myFile = myFile;
	}

	public String getMyFileFileName() {
		return myFileFileName;
	}
	public void setMyFileFileName(String myFileFileName) {
		this.myFileFileName = myFileFileName;
	}
	public WorkcardService getWorkcardService() {
		return workcardService;
	}

	public void setWorkcardService(WorkcardService workcardService) {
		this.workcardService = workcardService;
	}

	public MainWorkCardOne getEntity() {
		return entity;
	}
	public void setEntity(MainWorkCardOne entity) {
		this.entity = entity;
	}

	public List<WorkCardOne_BZ> getWorkCardOneBZList() {
		return workCardOneBZList;
	}

	public void setWorkCardOneBZList(List<WorkCardOne_BZ> workCardOneBZList) {
		this.workCardOneBZList = workCardOneBZList;
	}

	public InputStream getReturnStream() {
		return returnStream;
	}
	public void setReturnStream(InputStream returnStream) {
		this.returnStream = returnStream;
	}
	public String getDownFileName() {
		return downFileName;
	}
	public void setDownFileName(String downFileName) {
		this.downFileName = downFileName;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}

	public List<Ryzzfg> getRyzzfgList() {
		return ryzzfgList;
	}

	public void setRyzzfgList(List<Ryzzfg> ryzzfgList) {
		this.ryzzfgList = ryzzfgList;
	}

	public List<Wxdfx> getWxdfxList() {
		return wxdfxList;
	}

	public void setWxdfxList(List<Wxdfx> wxdfxList) {
		this.wxdfxList = wxdfxList;
	}

	public String getDirectFlag() {
		return directFlag;
	}

	public void setDirectFlag(String directFlag) {
		this.directFlag = directFlag;
	}

	public String getBdzid() {
		return bdzid;
	}

	public void setBdzid(String bdzid) {
		this.bdzid = bdzid;
	}

	public String getPicUrl() {
		return picUrl;
	}

	public void setPicUrl(String picUrl) {
		this.picUrl = picUrl;
	}

	
}
